<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import * as echarts from "echarts";

const props = defineProps({
  // Y轴数据（设备名称）
  yAxisData: {
    type: Array,
    required: true,
    default: () => [],
  },
  // 系列数据数组
  series: {
    type: Array,
    required: true,
    default: () => [],
    validator: (value) => {
      return (
        Array.isArray(value) &&
        value.every((series) => series.name && Array.isArray(series.data))
      );
    },
  },
  // 默认颜色集合
  colors: {
    type: Array,
    default: () => [
      "#16CA46",
      "#1890FF",
      "#FADB14",
      "#FA8C16",
      "#722ED1",
      "#EB2F96",
    ],
  },
  // 轴线颜色
  axisColor: {
    type: String,
    default: "#586FA2",
  },
  // 网格线颜色
  gridColor: {
    type: String,
    default: "#223151",
  },
  // 是否显示标签
  showLabel: {
    type: Boolean,
    default: true,
  },
  // 是否堆叠
  isStack: {
    type: Boolean,
    default: false,
  },
  // 是否显示背景
  showBackground: {
    type: Boolean,
    default: true,
  },
  // 是否显示图例
  showLegend: {
    type: Boolean,
    default: true,
  },
  // 图例位置
  legendPosition: {
    type: String,
    default: "top",
    validator: (value) => ["top", "bottom", "left", "right"].includes(value),
  },
  // 条形宽度
  barWidth: {
    type: [String, Number],
    default: 20,
  },
  // 是否显示工具提示
  showTooltip: {
    type: Boolean,
    default: true,
  },
});

const chartContainer = ref();
let chart = null;

// 计算图例位置
const legendPositionConfig = computed(() => {
  switch (props.legendPosition) {
    case "top":
      return { top: 10, left: "center", orient: "horizontal" };
    case "bottom":
      return { bottom: 10, left: "center", orient: "horizontal" };
    case "left":
      return { left: 10, top: "center", orient: "vertical" };
    case "right":
      return { right: 10, top: "center", orient: "vertical" };
    default:
      return { top: 10, left: "center", orient: "horizontal" };
  }
});

// 获取系列颜色
const getSeriesColor = (index) => {
  return (
    props.series[index]?.color || props.colors[index % props.colors.length]
  );
};

// 初始化图表配置
const getChartOption = () => {
  return {
    backgroundColor: "transparent",
    tooltip: {
      trigger: "axis",
    },
    legend: {
      show: props.showLegend && props.series.length > 1,
      data: props.series.map((item) => item.name),
      textStyle: {
        color: props.axisColor,
      },
      ...legendPositionConfig.value,
    },
    grid: {
      top: props.showLegend && props.legendPosition === "top" ? "5%" : "4%",
      left: props.showLegend && props.legendPosition === "left" ? "5%" : "4%",
      right: props.showLegend && props.legendPosition === "right" ? "5%" : "4%",
      bottom:
        props.showLegend && props.legendPosition === "bottom" ? "5%" : "4%",
      containLabel: true,
    },
    xAxis: {
      type: "value",
      boundaryGap: false,
      max: 10,
      axisLine: {
        lineStyle: {
          color: props.axisColor,
        },
      },
      splitLine: {
        lineStyle: {
          color: props.gridColor,
        },
      },
    },
    yAxis: {
      type: "category",
      data: props.yAxisData,
      axisTick: {
        lineStyle: {
          color: props.axisColor,
        },
        show: false,
      },
      axisLine: {
        lineStyle: {
          color: props.axisColor,
        },
        show: false,
      },
      axisLabel: {
        color: props.axisColor,
      },
    },
    series: props.series.map((item, index) => ({
      name: item.name,
      type: "bar",
      stack: props.isStack ? "total" : undefined,
      data: item.data,
      itemStyle: {
        color: item.color || getSeriesColor(index),
      },
      showBackground: props.showBackground,
      backgroundStyle: {
        color: "rgba(22, 202, 70, 0.1)",
      },
      // label: {
      //   show: props.showLabel,
      //   position: "right",
      //   color: props.axisColor,
      //   valueAnimation: true,
      //   formatter: (params) => {
      //     return params.value;
      //   },
      // },
      barWidth: props.barWidth,
      emphasis: {
        focus: "series",
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: "rgba(0, 0, 0, 0.5)",
        },
      },
    })),
  };
};

// 初始化图表
const initChart = () => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value);
    updateChart();
  }
};

// 更新图表数据
const updateChart = () => {
  if (chart) {
    chart.setOption(getChartOption(), true);
  }
};

// 响应窗口大小变化
const handleResize = () => {
  chart?.resize();
};

// 监听数据变化
watch(
  () => [props.yAxisData, props.series],
  () => {
    updateChart();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
  window.addEventListener("resize", handleResize);
});

onUnmounted(() => {
  chart?.dispose();
  window.removeEventListener("resize", handleResize);
});
</script>

<template>
  <div ref="chartContainer" class="chart-container"></div>
</template>

<style lang="scss" scoped>
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;
}
</style>